import { NextRequest } from 'next/server';

// 存储活跃的SSE连接
const connections = new Map<string, {
  controller: ReadableStreamDefaultController,
  heartbeatInterval: NodeJS.Timeout,
  createdAt: number
}>();

// 清理超时连接
const cleanupOldConnections = () => {
  const now = Date.now();
  const maxAge = 10 * 60 * 1000; // 10分钟
  
  for (const [connectionId, connection] of connections.entries()) {
    if (now - connection.createdAt > maxAge) {
      console.log(`🧹 Cleaning up old connection [${connectionId}]`);
      clearInterval(connection.heartbeatInterval);
      try {
        connection.controller.close();
      } catch (error) {
        // 忽略关闭错误
      }
      connections.delete(connectionId);
    }
  }
};

// 每5分钟清理一次旧连接
setInterval(cleanupOldConnections, 5 * 60 * 1000);

export async function GET(request: NextRequest) {
  // 限制最大连接数
  if (connections.size >= 10) {
    console.log(`⚠️ Too many SSE connections (${connections.size}), rejecting new connection`);
    return new Response('Too many connections', { status: 429 });
  }
  
  console.log('🔌 New SSE connection request');
  
  const connectionId = Math.random().toString(36).substring(2, 15);
  
  const stream = new ReadableStream({
    start(controller) {
      console.log(`🚀 Starting SSE stream [${connectionId}]`);
      
      // 先添加到连接池（临时，没有heartbeatInterval）
      connections.set(connectionId, {
        controller,
        heartbeatInterval: null as any, // 临时占位
        createdAt: Date.now()
      });
      
      // 设置心跳
      const heartbeatInterval = setInterval(() => {
        try {
          const connection = connections.get(connectionId);
          if (!connection) {
            clearInterval(heartbeatInterval);
            return;
          }
          
          // 检查controller状态
          try {
            if (controller.desiredSize === null) {
              console.log(`🔌 Controller closed, cleaning up [${connectionId}]`);
              clearInterval(heartbeatInterval);
              connections.delete(connectionId);
              return;
            }
          } catch (controllerError) {
            console.log(`🔌 Controller error, cleaning up [${connectionId}]:`, controllerError);
            clearInterval(heartbeatInterval);
            connections.delete(connectionId);
            return;
          }
          
          // 尝试发送心跳数据
          try {
            const heartbeatData = JSON.stringify({
              type: 'heartbeat',
              timestamp: new Date().toISOString(),
              connectionId
            });
            
            controller.enqueue(`data: ${heartbeatData}\n\n`);
            console.log(`💓 Heartbeat sent [${connectionId}]`);
          } catch (enqueueError) {
            console.log(`🔌 Failed to send heartbeat, controller likely closed [${connectionId}]`);
            clearInterval(heartbeatInterval);
            connections.delete(connectionId);
            return;
          }
        } catch (error) {
          console.error(`💥 Heartbeat error [${connectionId}]:`, error);
          clearInterval(heartbeatInterval);
          connections.delete(connectionId);
        }
      }, 30000);
      
      // 更新连接池，添加heartbeatInterval
      connections.set(connectionId, {
        controller,
        heartbeatInterval,
        createdAt: Date.now()
      });
      console.log(`📊 Active connections: ${connections.size}`);
      
      // 发送初始连接消息
      const initialData = JSON.stringify({
        type: 'connected',
        message: 'Connected to ChainWatch real-time service',
        timestamp: new Date().toISOString(),
        connectionId
      });
      
      controller.enqueue(`data: ${initialData}\n\n`);
      console.log(`✅ Initial connection message sent [${connectionId}]`);
      
      // 清理函数
      return () => {
        console.log(`🔌 Closing SSE connection [${connectionId}]`);
        const connection = connections.get(connectionId);
        if (connection) {
          clearInterval(connection.heartbeatInterval);
        connections.delete(connectionId);
        }
        console.log(`📊 Active connections: ${connections.size}`);
      };
    }
  });
  
  return new Response(stream, {
    headers: {
      'Content-Type': 'text/event-stream',
      'Cache-Control': 'no-cache',
      'Connection': 'keep-alive',
      'Access-Control-Allow-Origin': '*',
      'Access-Control-Allow-Methods': 'GET',
      'Access-Control-Allow-Headers': 'Cache-Control',
    },
  });
}

// 广播消息给所有连接
export function broadcastSSE(data: any) {
  if (connections.size === 0) return;
  
  const message = `data: ${JSON.stringify(data)}\n\n`;
  let broadcastCount = 0;
  
  for (const [connectionId, connection] of connections.entries()) {
    try {
      // 检查controller状态
      if (connection.controller.desiredSize === null) {
        console.log(`🔌 Controller closed during broadcast, cleaning up [${connectionId}]`);
        clearInterval(connection.heartbeatInterval);
        connections.delete(connectionId);
        continue;
      }
      
      connection.controller.enqueue(message);
      broadcastCount++;
      } catch (error) {
      console.error(`💥 Broadcast error [${connectionId}]:`, error);
      clearInterval(connection.heartbeatInterval);
      connections.delete(connectionId);
    }
    }
    
  if (broadcastCount > 0) {
    console.log(`📡 Broadcasted to ${broadcastCount} connections`);
  }
}